package com.example.smartmedicalsystem.controller;

import com.example.smartmedicalsystem.entity.*;
import com.example.smartmedicalsystem.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/doctor")
@RequiredArgsConstructor
public class DoctorController {
    private final DoctorRepository doctorRepository;
    private final AppointmentRepository appointmentRepository;
    private final MedicalRecordRepository medicalRecordRepository;
    private final MessageRepository messageRepository;
    private final MedicineRepository medicineRepository;
    private final UserRepository userRepository;

    @GetMapping("/appointments")
    public List<Appointment> getAppointments(Authentication authentication) {
        String username = authentication.getName();
        Doctor doctor = doctorRepository.findByUser_Username(username)
                .orElseThrow(() -> new RuntimeException("医生信息不存在"));
        return appointmentRepository.findByDoctorAndStatus(doctor, Appointment.Status.PENDING);
    }

    @PutMapping("/appointments/{appointmentId}/complete")
    public ResponseEntity<?> completeAppointment(
            @PathVariable Long appointmentId,
            @RequestParam String diagnosis,
            @RequestParam String prescription,
            @RequestBody List<MedicineRequest> medicines) {
        Appointment appointment = appointmentRepository.findById(appointmentId)
                .orElseThrow(() -> new RuntimeException("预约不存在"));
        for (MedicineRequest req : medicines) {
            Medicine medicine = medicineRepository.findById(req.medicineId())
                    .orElseThrow(() -> new RuntimeException("药品不存在"));
            if (medicine.getStock() < req.quantity()) {
                return ResponseEntity.badRequest().body(medicine.getName() + "库存不足");
            }
        }
        appointment.setStatus(Appointment.Status.COMPLETED);
        appointmentRepository.save(appointment);
        MedicalRecord record = new MedicalRecord();
        record.setAppointment(appointment);
        record.setDiagnosis(diagnosis);
        record.setPrescription(prescription);
        MedicalRecord savedRecord = medicalRecordRepository.save(record);
        medicines.forEach(req -> {
            Medicine medicine = medicineRepository.findById(req.medicineId()).get();
            medicine.setStock(medicine.getStock() - req.quantity());
            medicineRepository.save(medicine);
            Message msg = new Message();
            msg.setContent("处方药品已开具：" + medicine.getName() + " x" + req.quantity());
            msg.setReceiver(appointment.getPatient());
            messageRepository.save(msg);
        });
        return ResponseEntity.ok(savedRecord);
    }

    @PutMapping("/appointments/{id}/confirm")
    public ResponseEntity<Appointment> confirmAppointment(@PathVariable Long id) {
        Appointment app = appointmentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("预约不存在"));
        app.setStatus(Appointment.Status.CONFIRMED);
        Appointment saved = appointmentRepository.save(app);
        Message msg = new Message();
        msg.setContent("您的预约 " + id + " 已被医生确认");
        msg.setReceiver(saved.getPatient());
        messageRepository.save(msg);
        return ResponseEntity.ok(saved);
    }

    @GetMapping("/messages")
    public List<Message> getDoctorMessages(Authentication authentication) {
        User user = userRepository.findByUsername(authentication.getName());
        return messageRepository.findByReceiverOrderByCreatedAtDesc(user);
    }

    @GetMapping("/medicines")
    public List<Medicine> getMedicines() {
        return medicineRepository.findAll();
    }

    public record MedicineRequest(Long medicineId, int quantity) {}
}